package com.thundersoft.pickcolor.activity;

import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.thundersoft.pickcolor.R;
import com.thundersoft.pickcolor.database.DatabaseHelper;
import com.thundersoft.pickcolor.utils.MD5Util;
import com.thundersoft.pickcolor.utils.ShareUtils;

import es.dmoral.toasty.Toasty;

/**
 * 用户信息修改页面
 */
public class UserInfoActivity extends AppCompatActivity {
    private TextView username,userpwd,usersex,userage;
    private DatabaseHelper mDatabaseHelper;
    private SQLiteDatabase mSQLiteDatabase;
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 显示返回键
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mContext = this;
        setContentView(R.layout.activity_user_info);
        mDatabaseHelper = new DatabaseHelper(this,"PickColor.db",
                null,1);
        username = findViewById(R.id.username);
        usersex = findViewById(R.id.usersex);
        userpwd = findViewById(R.id.userpwd);
        userage = findViewById(R.id.userage);
        initUserInfo();

        View user_pwdlayout = findViewById(R.id.user_pwdlayout);
        user_pwdlayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSingleAlertDialogpwd(v);
            }
        });

        // 设置年龄
        View muser_agelayout = findViewById(R.id.user_agelayout);
        muser_agelayout.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showSingleAlertDialogage(v);
            }
        });

        // 设置姓名
        View muser_namelayout = findViewById(R.id.user_namelayout);
        muser_namelayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSingleAlertDialogname(v);
            }
        });

        // 设置性别
        View muser_sexlayout = findViewById(R.id.user_sexlayout);
        muser_sexlayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // 显示选择框方法
                showSingleAlertDialogsex(v);
            }
        });
    }

    /**
     * 初始化用户信息
     */
    private void initUserInfo() {
        // 用户名
        username.setText(ShareUtils.getString(mContext,"username",""));

        // 密码
        userpwd.setText("******");

        // 性别
        usersex.setText(ShareUtils.getString(mContext,"sex",""));

        // 年龄
        userage.setText(String.valueOf(ShareUtils.getInt(mContext,"age",0)));

    }

    // 弹出选择性别方法
    public void showSingleAlertDialogsex(View view){
        final String[] items = {getString(R.string.male_string), getString(R.string.female)};
        final int[] position = {0};
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setTitle(R.string.choice_sex_string);
        alertBuilder.setSingleChoiceItems(items,0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toasty.info(mContext,items[i]);
                position[0] = i;
            }
        }).setPositiveButton(R.string.yes_string, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                TextView usersex = findViewById(R.id.usersex);
                usersex.setText(items[position[0]]);
                ShareUtils.putString(mContext,"sex",items[position[0]]);
                ContentValues values = new ContentValues();
                values.put("sex", items[position[0]]);
                mSQLiteDatabase = mDatabaseHelper.getWritableDatabase();
                mSQLiteDatabase.update("user", values, "name = ?",
                        new String[]{ShareUtils.getString(mContext,"username","")});
            }
        }).setNegativeButton(R.string.cancel_string,null).show();
    }
    public void showSingleAlertDialogage(View view){
        final String[] ageArr = new String[200];
        for (int i = 0; i < 200; i++) {
            ageArr[i] = String.valueOf(i);
        }
        final int[] position = {0};
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setTitle(R.string.choice_age_string);
        alertBuilder.setSingleChoiceItems(ageArr,0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toasty.info(mContext,ageArr[i]);
                position[0] = i;
            }
        }).setPositiveButton(R.string.yes_string, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                TextView userage = findViewById(R.id.userage);
                userage.setText(ageArr[position[0]]);
                ShareUtils.putInt(mContext,"age",Integer.valueOf(ageArr[position[0]]));
                ContentValues values = new ContentValues();
                values.put("age", Integer.valueOf(ageArr[position[0]]));
                mSQLiteDatabase = mDatabaseHelper.getWritableDatabase();
                mSQLiteDatabase.update("user", values, "name = ?",
                        new String[]{ShareUtils.getString(mContext,"username","")});
            }
        }).setNegativeButton(R.string.cancel_string,null).show();
    }
    public void showSingleAlertDialogname(View view){
        final EditText et = new EditText(this);
        new AlertDialog.Builder(this).setTitle(R.string.reset_username_string)
                .setIcon(R.drawable.pickcolor_small_icon)
                .setView(et)
                .setPositiveButton(R.string.yes_string, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if(querySQLite(et.getText().toString())) {
                            //按下确定键后的事件
                            Toasty.info(getApplicationContext(), et.getText().toString());
                            TextView username = findViewById(R.id.username);
                            username.setText(et.getText().toString());
                            ContentValues values2 = new ContentValues();
                            values2.put("name", et.getText().toString());
                            mSQLiteDatabase = mDatabaseHelper.getWritableDatabase();
                            mSQLiteDatabase.update("user", values2, "name = ?",
                                    new String[]{ShareUtils.getString(mContext,"username","")});
                            ShareUtils.putString(mContext,"username",et.getText().toString());
                        }
                    }
                }).setNegativeButton(R.string.cancel_string,null).show();
    }

    public void showSingleAlertDialogpwd(View v){
        final EditText et = new EditText(this);
        new AlertDialog.Builder(this).setTitle(R.string.reset_pwd_string)
                .setIcon(R.drawable.pickcolor_small_icon)
                .setView(et)
                .setPositiveButton(R.string.yes_string, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //按下确定键后的事件
                        ContentValues values = new ContentValues();
                        values.put("password", MD5Util.encrypt(et.getText().toString()));
                        mSQLiteDatabase = mDatabaseHelper.getWritableDatabase();
                        mSQLiteDatabase.update("user", values, "name = ?",
                                new String[]{ShareUtils.getString(mContext,"username","")});
                        Toasty.success(mContext,R.string.modify_pwd_succeed_string);
                    }
                }).setNegativeButton(R.string.cancel_string,null).show();
    }

    /**
     * 判断用户名是否存在
     * @param username
     * @return
     */
    public boolean querySQLite(String username){
        mSQLiteDatabase = mDatabaseHelper.getWritableDatabase();
        Cursor cursor = null;
        try {
            cursor = mSQLiteDatabase.query("User",null,"name = ?",
                    new String[]{username},null,null,null);
            if(cursor.moveToFirst()){
                // 数据库有该用户，不可以修改用户名
                return false;
            }else {
                // 数据库没有该用户，可以修改用户名
                return true;
            }
        }catch (Exception e){
            return false;
        }finally {
            cursor.close();
        }
    }

    // 菜单栏操作
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

}